<?php
declare(strict_types=1);

namespace app\admin\controller\system;

use app\admin\model\Admin as AdminModel;
use app\admin\model\AdminSettings;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthGroupAccessModel;
use app\common\Attribute\ClassTitle;
use app\common\Attribute\RequestMethod;
use app\common\Attribute\RequestTitle;
use app\common\controller\AmisAdminController;
use hg\apidoc\annotation as Apidoc;
use LhpAmis\Renderers\Amis;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Request;
/**
 * 账号管理
 */
#[ClassTitle("账号")]
class Admin extends AmisAdminController
{
    /**
     * 列表
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function index(Request $request)
    {
        if ($request->isPost()) {

            $start = (int) $request->param('start', 0);
            $limit = (int) $request->param('limit', 10);
            $order = $request->param('order', 'ASC');
            $wheres = [];
            $query = AdminModel::where($wheres);
            $data = $query->limit($start, $limit)->order('create_time', $order)->paginate();
            return $this->data($data);
        }
        $amis = Amis::make()->TableBuilder()
            ->setTitle('列表')
            ->setSearchItems([
                ['name', '账号名称'],
                ['nickname', '账号昵称'],
                ['introduce', '简介'],
                ['create_time', '创建时间', 'date'],
            ])
            ->addColumns([
                ['id', 'ID'],
                ['avatar', '头像', 'avatar', '', '', ['src' => '${avatar}']],
                ['name', '账号名称'],
                ['nickname', '账号昵称'],
                ['introduce', '简介'],
                ['create_time', '创建时间', 'date'],
                ['right_button', '操作', 'btn'],
            ])
            ->addTopButtons('create,delete')
            ->addRightButtons('edit,delete')
            ->addRightButtons([
                $this->rowCustomButton($this->BaseApiGet('access', ['id' => '${id}']), '授权'),
                $this->rowCustomButton($this->BaseApiGet('modifyPassword', ['id' => '${id}']), '修改密码'),
            ])
        ;
        return $this->data($amis);
    }

    /**
     * 创建
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('创建')]
    public function create(): \think\response\Json
    {
        if ($this->request->isPost()) {
            $data = $this->request->all();
            try {
                $this->validate($data, [
                    'name' => 'require|alphaNum',
                ], [
                    'name.require' => '账号必须',
                    'name.alphaNum' => '账号错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = AdminModel::make()->create([
                'name' => $data['name'],
                'nickname' => $data['nickname'],
                'introduce' => $data['introduce'],
            ]);
            if ($result->isEmpty()) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }

        $amis = Amis::make()->FormBuilder()
            ->addFormItems([
                ['avatar', '头像', 'avatar'],
                ['name*', '账号名称'],
                ['nickname*', '账号昵称'],
                ['introduce', '简介'],
            ]);
        return $this->data($amis);

    }

    /**
     * 修改密码
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('修改密码')]
    public function modifyPassword(Request $request): \think\response\Json
    {
        if ($request->isPost()) {

            $data = $request->all();
            try {
                $validateRule = [
                    'id' => [
                        'require' => '账号必须',
                        'alphaNum' => '账号错误',
                        'length:32'
                    ],
                    'password' => [
                        'length:32',
                        'require' => '密码必须',
                        'alphaNum' => '密码错误',
                    ],
                ];
                $this->validate($data, [
                    'id' => 'require|alphaNum|length:32',
                    'password' => 'require|alphaNum|length:32',
                ], [
                    'id.require' => '账号必须',
                    'id.alphaNum' => '账号错误',
                    'password.require' => '密码必须',
                    'password.alphaNum' => '密码错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $password = AdminModel::password($data['password']);
            $result = AdminModel::where('id', $data['id'])
                ->find()
                ->save([
                    'password' => $password['password'],
                    'password_salt' => $password['salt'],
                ]);
            if ($result === false) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $amis = Amis::make()->FormBuilder()
            ->setTitle('修改密码')
            ->setApi(BaseApiPost('modifyPassword'))
            ->addFormItems([
                ['id', 'Id', 'hidden'],
                ['password', '密码', 'password'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }

    /**
     * 用户设置保存
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('用户设置')]
    public function userSetting(Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            $data = $request->all();
            try {
                $this->validate($data, [
                    'name' => 'require|alphaNum',
                ], [
                    'name.require' => '账号必须',
                    'name.alphaNum' => '账号错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = AdminModel::make()->create([
                'name' => $data['name'],
                'nickname' => $data['nickname'],
                'introduce' => $data['introduce'],
            ]);
            if ($result->isEmpty()) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $userInfo = app('auth-admin')->getData();

        $row = AdminModel::where('id', $userInfo['id'])->findOrEmpty()->toArray();
        // dump([ $row,AdminModel::getLastSql()]);die;
        $amis = Amis::make()->FormBuilder()
            ->setTitle('创建')
            ->data($row)
            ->addFormItems([
                ['avatar', '头像', 'image'],
                ['name', '账号名称'],
                ['nickname', '账号昵称'],
                ['introduce', '简介', 'textarea'],
            ]);
        return $this->data(Amis::make()->Page()->body($amis));
    }
    /**
     * 更新
     * @param string $id
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('更新')]
    public function update(Request $request): \think\response\Json
    {
        try {
            $admin = AdminModel::where('id', $request->param('id'))->findOrEmpty();
            if ($admin->isEmpty()) {
                return $this->error('账号不存在');
            }
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error('账号不存在');
        }

        if ($request->isPost()) {

            $data = $request->all();

            try {
                $this->validate($data, [
                    'name' => 'require|alphaNum',
                ], [
                    'name.require' => '账号必须',
                    'name.alphaNum' => '账号错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }

            $save = [
                'name' => $data['name'],
                'avatar' => $data['avatar'],
                'nickname' => $data['nickname'],
                'introduce' => $data['introduce'],
            ];
            if (strlen((string) $save['avatar']) > 10) {
                unset($save['avatar']);
            }
            $result = $admin->save($save);
            if (!$result) {
                return $this->error('更新失败');
            }

            return $this->success('更新成功', [getLastSql()]);
        }

        $amis = Amis::make()->FormBuilder()
            ->setTitle('更新')
            ->data($admin->toArray())
            ->addFormItems([
                ['id', 'ID', 'hidden'],
                ['avatar', '头像', 'image'],
                ['name', '账号名称'],
                ['nickname', '账号昵称'],
                ['introduce', '简介'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }


    /**
     * 删除
     */
    #[RequestMethod(['DELETE'])]
    #[RequestTitle('删除')]
    public function delete(string $id): \think\response\Json
    {
        try {
            //code...

            $row = AdminModel::where('id', $id)->find();
            if (!$row) {
                return $this->error('错误');
            }
            $row->delete();

            return $this->success('成功');
        } catch (\Throwable $th) {
            return $this->error('错误:' . $th->getMessage());
        }
    }

    /**
     * 授权
     * @param string $id
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('授权')]
    public function access(string $id, Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            $data = $request->all();
            // 删除
            $accessArr = AuthGroupAccessModel::where('admin_id', $id)->select()->toArray();
            foreach ($accessArr as $access) {
                AuthGroupAccessModel::where('id', $access['id'])->find()->delete();
            }
            $group_ids = explode(',', $data['group_id']) ?: [];
            $install = [];
            foreach ($group_ids as $itemId) {
                $install[] = [
                    'admin_id' => $id,
                    'group_id' => $itemId,
                ];
            }
            try {
                AuthGroupAccessModel::make()->saveAll($install);
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }

            return $this->success('成功');
        }
        $group_ids = AuthGroupAccessModel::where(['admin_id' => $id])->column('group_id');
        $group_id = join(',', $group_ids);
        $data = [
            'admin_id' => $id,
            'group_id' => $group_id,
        ];
        $amis = Amis::make()->FormBuilder()
            ->setTitle('授权')
            ->data($data)
            ->addFormItems([
                ['id', '用户ID', 'hidden', '', $id],
                ['group_id', '授权', 'select', '', '', AuthGroupModel::getAuthGroupList(), ['multiple' => true, 'checkAll' => true]],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }

    /**
     * 角色列表
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('角色')]
    public function group(Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            $order = $request->param('order', 'ASC');
            $query = new AuthGroupModel();
            $total = $query->count();
            $data = $query->order('create_time', $order)->select();

            return $this->success('', [
                'data' => $data,
                'total' => $total,
            ]);
        }
        $amis = Amis::make()->FormBuilder()
            ->setTitle('角色列表')
            ->setApi(BaseApiPost('table')) //api获取表单填充数据
            ->addFormItems([
                ['avatar', '头像', 'image'],
                ['name', '账号名称'],
                ['nickname', '账号昵称'],
                ['introduce', '简介'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }

    /**
     * 角色列表
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('保存用户配置')]
    public function save_setting(Request $request)
    {
        if ($request->isPost()) {
            try {
                $data = $request->getContent();

                AdminSettings::setUserSettings($this->getUserId(), json_decode($data, true));

                return $this->success();
            } catch (\Throwable $th) {
                return $this->error('保存失败：' . $th->getMessage(), $th->getTrace());
            }
        }
        return $this->error('请求错误');
    }
}